﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Net;
using System.Security.Claims;
using System.Text;
using XinLife.Application.Interface;
using XinLife.Common.Filters;
using XinLife.Common.SignalR;
using XinLife.Core.Helper;
using XinLife.Model;

namespace XinLife.Common
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class AuthorizeAttribute : Microsoft.AspNetCore.Authorization.AuthorizeAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 接口权限验证
        /// </summary>
        /// <param name="authorizationFilterContext"></param>
        public void OnAuthorization(AuthorizationFilterContext authorizationFilterContext)
        {
            var context = authorizationFilterContext.HttpContext;
            var endpoint = context.GetEndpoint();
            if (endpoint != null)
            {
                var isHasAllowAnonymous = endpoint.Metadata.GetMetadata<AllowAnonymousAttribute>() != null;

                if (!isHasAllowAnonymous)
                {
                    //请求Url
                    var questUrl = context.Request.Path.ToString().ToLower();

                    var _authorizeService = authorizationFilterContext.HttpContext.RequestServices.GetService<IAuthorizeService>();
                    var result = _authorizeService.GetRoleModule().Result;

                    var requirement = (from item in result
                                       orderby item.cId
                                       select new
                                       {
                                           Url = item.ModuleButton?.cApi,
                                           Role = item.Role?.cName,
                                       }).ToList();

                    //判断请求的url是否在所有的权限中
                    if (requirement.Exists(g => g.Url?.ToLower() == questUrl))
                    {
                        // 获取当前用户的角色
                        var currentUserRoles = AspNetUser.User.Roles.Select(i => i.cName).ToList();
                        //验证权限
                        if (!requirement.Exists(t => currentUserRoles.Contains(t.Role) && t.Url?.ToLower() == questUrl))
                        {
                            // 用户没有足够的权限，返回验证失败
                            var customResult = new ObjectResult("您请求的接口没有授权哩！")
                            {
                                StatusCode = (int)HttpStatusCode.Forbidden
                            };
                            authorizationFilterContext.Result = customResult;
                            return;
                        }
                    }
                    else
                    {
                        //Uri.UnescapeDataString();
                        //这里做数据加解密
                        //var request = authorizationFilterContext.HttpContext.Request;
                        //request.EnableBuffering();
                        //var requestReader = new StreamReader(request.Body);
                        //var requestContent = requestReader.ReadToEnd();
                        //request.Body.Position = 0;
                        //request.QueryString = request.QueryString.Add("aaa", "2222");

                        //待所有api添加后再放开
                        //authorizationFilterContext.Result = new ForbidResult();
                        //return;
                    }
                }
            }
        }
    }
}
